package de.slothsoft.commons.swing;

import java.util.prefs.Preferences;

import javax.swing.JComponent;

import de.slothsoft.commons.res.CommonMessages;

public class PreferenceLoginPanel extends LoginPanel {

    private static final long serialVersionUID = 1L;

    private static final String PREFERENCE_LOGIN = "LoginPanel.login";
    private static final String PREFERENCE_PASSWORD = "LoginPanel.password";
    private static final String PREFERENCE_REMEMBER = "LoginPanel.remember";

    private final Preferences preferences;

    public PreferenceLoginPanel(JComponent afterLoginComponent, LoginProvider loginProvider, Preferences preferences) {
	this(createDefaultUser(preferences), afterLoginComponent, loginProvider, preferences);
    }

    public PreferenceLoginPanel(ExtendedUser user, JComponent afterLoginComponent, LoginProvider loginProvider,
	    Preferences preferences) {
	super(user, afterLoginComponent, loginProvider);

	this.preferences = preferences;
	if (user.isRemembered()) {
	    automaticallyLogin();
	}
    }

    @Override
    protected JComponent createLoginGroup() {
	JComponent group = super.createLoginGroup();
	createLabel(group, CommonMessages.getString("Login.remember"), 0, 2);
	createCheckBox(group, "Remembered", 1, 2);
	return group;
    }

    @Override
    protected void performSuccessfulLogin() {
	super.performSuccessfulLogin();
	ExtendedUser user = (ExtendedUser) getModel();
	storeUser(this.preferences, user);
    }

    private void automaticallyLogin() {
	User user = getModel();
	if (getLoginProvider().login(user.getLogin(), user.getPassword())) {
	    performSuccessfulLogin();
	}
    }

    /*
	 * 
	 */

    public static ExtendedUser createDefaultUser(Preferences preferences) {
	User defaultUser = LoginPanel.createDefaultUser();

	ExtendedUser user = new ExtendedUser();
	user.setRemembered(preferences.getBoolean(PREFERENCE_REMEMBER, false));
	user.setLogin(preferences.get(PREFERENCE_LOGIN, defaultUser.getLogin()));
	char[] defaultPassword = defaultUser.getPassword();
	if (user.isRemembered()) {
	    user.setPassword(preferences.get(PREFERENCE_PASSWORD,
		    defaultPassword == null ? null : new String(defaultPassword)).toCharArray());
	} else {
	    user.setPassword(defaultPassword);
	}
	return user;
    }

    public static void storeUser(Preferences preferences, ExtendedUser user) {
	preferences.putBoolean(PREFERENCE_REMEMBER, user.isRemembered());
	preferences.put(PREFERENCE_LOGIN, user.getLogin());
	preferences.put(PREFERENCE_PASSWORD, new String(user.getPassword()));
    }

    public static class ExtendedUser extends User {

	private boolean remembered;

	public boolean isRemembered() {
	    return this.remembered;
	}

	public void setRemembered(boolean rememberMe) {
	    this.remembered = rememberMe;
	}

    }
}
